from io import BytesIO

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
import xlwt

from .models import Questionnaire, Question, Answer
from .forms import QuestionnaireForm,  QuestionForm


def index(request):
    questionnaire = Questionnaire.objects.get(id=1)
    question = Question.objects.all()
    count = 50 - Answer.objects.filter(question=31).count()
    return render(request, "ali_index.html", {'questionnaire_name': questionnaire.questionnaire_name, 'question': question, "count": count})


def set_(request):
    """
    问卷设置页面
    """
    if request.user.username in ['lee', 'admin']:
        questionnaire = Questionnaire.objects.get(id=1)
        question = Question.objects.all()
        return render(request, 'index.html', {'questionnaire_name': questionnaire.questionnaire_name, 'question': question})
    else:
        return HttpResponse('权限错误')


def download(request):
    """
    下载
    :param request:
    :return:
    """
    if request.user.username not in ['lee', 'admin']:
        return HttpResponse('权限错误')
    workbook = xlwt.Workbook(encoding='utf-8')
    title = Questionnaire.objects.get(id=1).questionnaire_name
    worksheet = workbook.add_sheet(title)
    head = Question.objects.all()
    for i in range(len(head)):
        worksheet.write(0, i, head[i].question_text)
        answer = Answer.objects.filter(question=head[i])
        for j in range(len(answer)):
            worksheet.write(j+1, i, answer[j].answer_text)

    out = BytesIO()
    workbook.save(out)
    out.seek(0)
    resp = HttpResponse(content_type='application/vnd.ms-excel')
    resp['Content-Disposition'] = 'attachment; filename={}.xls'.format(title)
    resp.write(out.getvalue())
    return resp


class QuestionnaireView(View):

    def get(self, request):
        """获取问卷"""
        questionnaire = Questionnaire.objects.get(id=1)
        question = Question.objects.all()
        return render(request, 'questionnaire.html', {'questionnaire_name': questionnaire.questionnaire_name, 'question': question})

    def post(self, request):
        if request.user.username not in ['lee', 'admin']:
            return HttpResponse('权限错误')
        requ = Questionnaire.objects.get(id=1)
        print(request.POST)
        form = QuestionnaireForm(instance=requ, data=request.POST)
        if form.is_valid():
            form.save()
            questionnaire = Questionnaire.objects.get(id=1)
            question = Question.objects.all()
            return render(request, 'qu_form.html',
                          {'questionnaire_name': questionnaire.questionnaire_name, 'question': question})
        else:
            return HttpResponse('失败')

    def delete(self, request):
        if request.user.username not in ['lee', 'admin']:
            return HttpResponse('权限错误')
        """删除问卷"""
        requ = Questionnaire.objects.get(id=1)
        requ.delete()
        Questionnaire.objects.create(id=1, questionnaire_name='默认名称')
        return HttpResponse('delete')


class QuestionView(View):
    """
    问卷问题
    """
    def post(self, request):
        print(request.POST)
        form = QuestionForm(request.POST)
        if form.is_valid():
            form.save()
            questionnaire = Questionnaire.objects.get(id=1)
            question = Question.objects.all()
            return render(request, 'qu_form.html', {'questionnaire_name': questionnaire.questionnaire_name, 'question': question})
        else:
            return HttpResponse('failed')

    def get(self):
        return HttpResponse('question')


def add_answer(request):
    """
    提交问卷
    :param request:
    :return:
    """
    if request.user.username not in ['lee', 'admin']:
        return HttpResponse('权限错误')
    a = request.POST.dict()
    for qu, ans in a.items():
        Answer.objects.create(question=Question.objects.get(id=int(qu)), answer_text=ans)
    return render(request, 'success.html')


def add_answer_go_on(request):
    """
    提交问卷
    :param request:
    :return:
    """
    print(request.POST.dict())
    a = request.POST.dict()
    for qu, ans in a.items():
        Answer.objects.create(question=Question.objects.get(id=int(qu)), answer_text=ans)

    # 跳转问卷页面
    return redirect('/questionaire/')

